<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="剧名" prop="play">
        <el-input
          v-model="queryParams.play"
          placeholder="请输入剧名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 类型查询条件改为下拉框 -->
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择类型"
          clearable
          style="width: 100px"
        >
          <el-option
            v-for="dict in dict.type.sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 是否剪辑查询条件改为下拉框 -->
      <el-form-item label="是否剪辑" prop="izEdit">
        <el-select
          v-model="queryParams.izEdit"
          placeholder="请选择"
          clearable
          style="width: 100px"
        >
          <el-option label="是" value="Y" />
          <el-option label="否" value="N" />
        </el-select>
      </el-form-item>

      <!-- 是否匹配片单查询条件改为下拉框 -->
      <el-form-item label="是否匹配片单" prop="izMatch" label-width="108px">
        <el-select
          v-model="queryParams.izMatch"
          placeholder="请选择"
          clearable
          style="width: 120px"
        >
          <el-option label="是" value="Y" />
          <el-option label="否" value="N" />
        </el-select>
      </el-form-item>

      <el-form-item label="链接是否空" prop="shUrl" label-width="108px">
        <el-select
          v-model="queryParams.shUrl"
          placeholder="请选择"
          clearable
          style="width: 120px"
        >
          <el-option label="是" value="Y" />
          <el-option label="否" value="N" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="copyrightList" @selection-change="handleSelectionChange" class="copyright-table">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="50"/>
      <el-table-column label="剧名" align="center" prop="play" width="280"/>
      <el-table-column label="类型" align="center" prop="type" width="80"/>
      <el-table-column label="集数" align="center" prop="episode" width="80"/>

      <!-- 链接列优化 -->
      <el-table-column label="链接" align="center" width="280">
        <template slot-scope="scope">
          <div class="text-ellipsis-cell">
            <el-tooltip
              :content="scope.row.shUrl || '无链接'"
              placement="top-start"
              effect="light"
              :disabled="!scope.row.shUrl"
              popper-class="custom-tooltip"
            >
              <span class="cell-text">
                {{ formatCellContent(scope.row.shUrl, 50) }}
              </span>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>

      <!-- 内容列优化 -->
      <el-table-column label="内容" align="center" width="500">
        <template slot-scope="scope">
          <div class="text-ellipsis-cell">
            <el-tooltip
              :content="scope.row.content || '无内容'"
              placement="top-start"
              effect="light"
              :disabled="!scope.row.content"
              popper-class="custom-tooltip"
            >
              <span class="cell-text">
                {{ formatCellContent(scope.row.content, 100) }}
              </span>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="是否剪辑" align="center" prop="izEdit" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.izEdit === 'Y' ? '是' : scope.row.izEdit === 'N' ? '否' : '-' }}</span>
        </template>
      </el-table-column>

<!--      <el-table-column label="是否匹配片单" align="center" prop="izMatch" width="120">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ scope.row.izMatch === 'Y' ? '是' : scope.row.izMatch === 'N' ? '否' : '-' }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="图片" align="center" prop="picUrl" width="100">-->
<!--        <template slot-scope="scope">-->
<!--          <image-preview :src="scope.row.copyPic" :width="50" :height="50"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="图片" align="center" prop="picUrl" width="100">
        <template slot-scope="scope">
          <image-preview
            v-if="scope.row.copyPic"
            :src="scope.row.copyPic"
            :width="50"
            :height="50"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="handleAssociate(scope.row)"
          >关联
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
          >下载
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改片单版权对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="剧名" prop="play">
          <el-input v-model="form.play" placeholder="请输入剧名" />
        </el-form-item>
        <el-form-item label="版权" prop="copyRight">
          <file-upload v-model="form.copyRight"/>
        </el-form-item>
        <el-form-item label="图片" prop="copyPic">
          <image-upload v-model="form.copyPic"/>
        </el-form-item>
        <!-- 是否剪辑改为下拉框 -->
        <el-form-item label="是否剪辑" prop="izEdit">
          <el-select
            v-model="form.izEdit"
            placeholder="请选择是否剪辑"
            clearable
            style="width: 100%"
          >
            <el-option label="是" value="Y" />
            <el-option label="否" value="N" />
          </el-select>
        </el-form-item>

        <!-- 修改后 -->
        <el-form-item label="剪辑人" prop="opId">
          <el-select
            v-model="form.opId"
            placeholder="请选择剪辑人"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 是否匹配片单改为下拉框 -->
        <!--        <el-form-item label="是否匹配片单" prop="izMatch">-->
        <!--          <el-select-->
        <!--            v-model="form.izMatch"-->
        <!--            placeholder="请选择是否匹配片单"-->
        <!--            clearable-->
        <!--            style="width: 100%"-->
        <!--          >-->
        <!--            <el-option label="是" value="Y" />-->
        <!--            <el-option label="否" value="N" />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->

        <el-form-item label="片单表主键ID" prop="playId">
          <el-input v-model="form.playId" placeholder="请输入片单表主键ID" />
        </el-form-item>
        <el-form-item label="版权方" prop="holder">
          <el-input v-model="form.holder" placeholder="请输入版权方" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 关联片单对话框 -->
    <el-dialog title="关联片单" :visible.sync="associateOpen" width="500px" append-to-body>
      <el-form ref="associateForm" :model="associateForm" label-width="80px">
        <el-form-item label="版权">
          <el-input v-model="associateForm.play" disabled />
        </el-form-item>
        <el-form-item label="关联片单" prop="searchName">
          <el-input
            v-model="associateForm.searchName"
            placeholder="请输入片单名称"
            clearable
            style="width: calc(100% - 80px); margin-right: 10px;"
            @keyup.enter.native="handleSearch"
          />
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleSearch"
            :loading="searchLoading"
          >搜索</el-button>
        </el-form-item>
        <el-form-item label="选择片单" prop="selectedItem" v-if="allList.length > 0">
          <el-select
            v-model="associateForm.selectedItem"
            placeholder="请选择片单"
            clearable
            style="width: 100%"
            @change="handleItemSelect"
          >
            <el-option
              v-for="item in allList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="allList.length === 0 && associateForm.searchName">
          <div style="color: #999; text-align: center;">暂无搜索结果</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAssociate" :disabled="!associateForm.coId">保 存</el-button>
        <el-button @click="associateOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addCopyright,
    delCopyright,
    getAllList,
    getChannelAdminList,
    getCopyright,
    listCopyright,
    updateCopyright
  } from "@/api/play/copyright"
  import download from '@/plugins/download'

  export default {
    name: "Copyright",
    dicts: ['sys_user_sex'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 片单版权表格数据
        copyrightList: [],
        // 用户列表数据（剪辑人）
        userList: [],
        // 片单列表数据
        allList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示关联弹出层
        associateOpen: false,
        // 搜索加载状态
        searchLoading: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          play: null,
          izEdit: null,
          izMatch: null,
          shUrl: null,
          type: null,
        },
        // 表单参数
        form: {},
        // 关联表单参数
        associateForm: {
          id: null,
          play: null,
          searchName: '',
          selectedItem: null,
          coId: null
        },
        // 表单校验
        rules: {
          play: [
            {message: "剧名不能为空", trigger: "blur"}
          ],

        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      /** 查询片单版权列表 */
      getList() {
        this.loading = true
        listCopyright(this.queryParams).then(response => {
          this.copyrightList = response.rows
          this.total = response.total
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      },

      /** 获取剪辑人列表 */
      getUserList() {
        getChannelAdminList().then(response => {
          if (response.code === 200) {
            this.userList = response.data || []
          } else {
            this.$modal.msgError("获取剪辑人列表失败")
            this.userList = []
          }
        }).catch(error => {
          console.error("获取剪辑人列表失败:", error)
          this.$modal.msgError("获取剪辑人列表失败")
          this.userList = []
        })
      },

      /** 搜索片单列表 */
      handleSearch() {
        if (!this.associateForm.searchName) {
          this.$modal.msgWarning("请输入片单名称")
          return
        }

        this.searchLoading = true
        getAllList({ name: this.associateForm.searchName }).then(response => {
          this.allList = response.data || []
          this.searchLoading = false
          if (this.allList.length === 0) {
            this.$message({
              message: '未找到匹配的片单',
              type: 'info',
              duration: 2000
            })
          } else {
            this.$modal.msgSuccess(`找到 ${this.allList.length} 个匹配的片单`)
          }
        }).catch(error => {
          console.error("搜索片单失败:", error)
          this.$modal.msgError("搜索失败")
          this.searchLoading = false
          this.allList = []
        })
      },

      /** 格式化单元格内容 */
      formatCellContent(content, maxLength) {
        if (!content) return '-'
        if (content.length <= maxLength) return content
        return content.substring(0, maxLength) + '...'
      },

      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },

      // 表单重置
      reset() {
        this.form = {
          id: null,
          play: null,
          copyRight: null,
          copyPic: null,
          izEdit: null,
          izMatch: null,
          opId: null,
          playId: null,
          holder: null,
          remark: null,
          createTime: null,
          createBy: null,
          updateBy: null,
          updateTime: null
        }
        this.resetForm("form")
      },

      // 关联表单重置
      resetAssociateForm() {
        this.associateForm = {
          id: null,
          play: null,
          searchName: '',
          selectedItem: null,
          coId: null
        }
        this.allList = []
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm")
        this.handleQuery()
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = "添加片单版权"
        this.getUserList()
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const id = row.id || this.ids
        getCopyright(id).then(response => {
          this.form = response.data
          this.open = true
          this.title = "修改片单版权"
          this.getUserList()
        })
      },

      /** 关联按钮操作 */
      handleAssociate(row) {
        this.resetAssociateForm()
        this.associateForm.id = row.id
        this.associateForm.play = row.play
        this.associateOpen = true
      },

      /** 下载按钮操作 */
      handleDownload(row) {
        const id = row.id
        this.$modal.confirm('是否确认下载该版权文件？').then(() => {
          return getCopyright(id)
        }).then(response => {
          // 使用下载插件
          if (response.data && response.data.copyRight) {
            // 去除 /profile/upload/ 前缀
            const filePath = response.data.copyRight.replace('/profile/upload', '')
            download.name(filePath)
            // download.name(response.data.copyRight)
          } else {
            this.$modal.msgError("下载文件信息不完整")
          }
        }).catch(error => {
          console.error("下载失败:", error)
          this.$modal.msgError("下载失败")
        })
      },

      /** 片单项选择变化 */
      handleItemSelect(value) {
        if (value) {
          const selectedItem = this.allList.find(item => item.id === value)
          if (selectedItem) {
            this.associateForm.coId = selectedItem.id
            this.associateForm.selectedItem = selectedItem.id
          }
        } else {
          this.associateForm.coId = null
          this.associateForm.selectedItem = null
        }
      },

      /** 提交关联 */
      submitAssociate() {
        if (!this.associateForm.coId) {
          this.$modal.msgError("请选择要关联的片单")
          return
        }

        const updateData = {
          id: this.associateForm.id,
          coId: this.associateForm.coId
        }

        updateCopyright(updateData).then(response => {
          this.$modal.msgSuccess("关联成功")
          this.associateOpen = false
          this.getList()
        }).catch(error => {
          this.$modal.msgError("关联失败")
        })
      },

      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateCopyright(this.form).then(response => {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.getList()
              }).catch(error => {
                console.error("修改失败:", error)
              })
            } else {
              addCopyright(this.form).then(response => {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              }).catch(error => {
                console.error("新增失败:", error)
              })
            }
          }
        })
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids
        this.$modal.confirm('是否确认删除片单版权编号为"' + ids + '"的数据项？').then(() => {
          return delCopyright(ids)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        }).catch(() => {})
      },

      /** 导出按钮操作 */
      handleExport() {
        this.download('play/copyright/export', {
          ...this.queryParams
        }, `copyright_${new Date().getTime()}.xlsx`)
      }
    }
  }
</script>

<style scoped>
  .app-container {
    padding: 20px;
  }

  /* 表格单元格文本省略样式 - 只针对当前页面的表格 */
  .copyright-table ::v-deep .text-ellipsis-cell {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    position: relative;
    z-index: 1;
  }

  .copyright-table ::v-deep .cell-text {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
    line-height: 1.5;
    cursor: pointer;
    pointer-events: auto;
  }

  /* 确保tooltip包装器正确 */
  .copyright-table ::v-deep .el-tooltip {
    width: 100%;
    height: 100%;
    display: block;
  }

  /* 鼠标悬浮效果增强 */
  .copyright-table ::v-deep .text-ellipsis-cell:hover .cell-text {
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  /* 表格样式 */
  .copyright-table ::v-deep .el-table__body-wrapper .el-table__body td {
    padding: 8px 0;
  }

  .copyright-table ::v-deep .el-table .cell {
    line-height: 1.5 !important;
    padding: 8px 0 !important;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .copyright-table ::v-deep .el-table__row {
    height: 48px !important;
  }

  .copyright-table ::v-deep .el-table__row td {
    height: 48px !important;
    max-height: 48px !important;
  }

  .copyright-table ::v-deep .el-table--medium .el-table__cell {
    padding: 8px 0 !important;
  }
</style>

<style>
  /* 增强的tooltip样式 */
  .custom-tooltip {
    max-width: 600px !important;
    max-height: 400px !important;
    overflow-y: auto !important;
    word-break: break-all !important;
    word-wrap: break-word !important;
    line-height: 1.6 !important;
    font-size: 14px !important;
    padding: 12px 16px !important;
    background-color: #fff !important;
    border: 1px solid #e4e7ed !important;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
    color: #606266 !important;
    z-index: 9999 !important;
  }

  .custom-tooltip[x-placement^="top"] .popper__arrow {
    border-top-color: #e4e7ed !important;
  }

  .custom-tooltip[x-placement^="top"] .popper__arrow::after {
    border-top-color: #fff !important;
  }
</style>
